/**
 * @author 蓝面小生
 * simpleUI子项目
 * simpleDialog 2.3
 */
(function(){
    Simple.declare("dialog.Modal", null, {
        color: "#000",
        opacity: 0.5,
        node: null,
        selectFix: false,
        init: function(){
            var s = this;
            if (s.node) {
                s._appendModal();
				$(window).bind("resize:modal",function(){
					s._appendModal();
				})
                $(window).resize(function(){
                    $(this).trigger("resize:modal");
                });
            }
        },
        _appendModal: function(){
            var s = this, docSize = Simple.getDoc(), overlayHandle, overlayMark, node = s.node, width, height, left, top, offset, position;
            if ($(".simple-modal")[0]) {
                overlayHandle = $(".simple-modal").show();
                overlayMark = overlayHandle.find(".simple-mark");
            }
            else {
                overlayHandle = $("<div/>").addClass("simple-modal");
                overlayMark = $("<div/>").addClass("simple-mark");
                overlayHandle.append(overlayMark).appendTo(document.body);
            }
            if (s.selectFix) {
                if (!overlayHandle.find("iframe")[0]) {
                    overlayHandle.append('<iframe src="javascript:;" class="simple-selectFix" frameBorder="0">');
                }
            }
            if (node == document.body) {
                width = "100%";
                height = "100%";
                left = 0;
                top = 0;
                position = "fixed";
                if (Simple.isIE6) {
                    height = docSize.h;
                    position = "absolute";
                }
            }
            else {
                offset = $(node).offset();
                width = $(node).outerWidth();
                height = $(node).outerHeight();
                left = offset.left;
                top = offset.top;
                position = "absolute";
            }
            overlayMark.css({
                background: s.color,
                opacity: s.opacity
            });
            overlayHandle.css({
                width: width,
                height: height,
                position: position,
                top: top,
                left: left,
                zIndex: 999
            })
            s.overlayHandle = overlayHandle;
            s.overlayMark = overlayMark;
        },
        destroy: function(){
            this.overlayHandle.hide();
			$(window).unbind("resize:modal");
        }
    });
    Simple.bridgeTojQuery("modal,simpleModal", Simple.dialog.Modal);
    
    Simple.mixin(Simple, {
        getDoc: function(){
            return {
                h: Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight),
                w: Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth)
            }
        },
        getClient: function(){
            return {
                h: document.documentElement.clientHeight,
                w: document.documentElement.clientWidth
            }
        },
        getSize: function(el, isModal){
            if (!(el instanceof jQuery)) {
                el = $(el);
            }
            if (el.is("body")) {
                if (isModal) {
                    return this.getDoc();
                }
                else {
                    return this.getClient();
                }
            }
            else {
                return {
                    h: el.outerHeight(),
                    w: el.outerWidth()
                }
            }
        }
    });
    Simple.position = {
        at: function(node, referNode, points){
            node = $(node);
            if (node.css("position") == "static") {
                node.css("position", "absolute");
            }
            var rfOffset = $(referNode).offset(), w = node.outerWidth(), h = node.outerHeight(), t, l, rfw = Simple.getSize(referNode).w, rfh = Simple.getSize(referNode).h;
            if (typeof points == "string") {
                switch (points) {
                    case "cc":
                        t = rfOffset.top + (rfh - h) / 2;
                        l = rfOffset.left + (rfw - w) / 2;
                        break;
                    case "rc":
                        t = rfOffset.top + (rfh - h) / 2;
                        l = rfOffset.left + rfw;
                        break;
                    case "bc":
                        t = rfOffset.top + rfh;
                        l = rfOffset.left + (rfw - w) / 2;
                        break;
                    case "lc":
                        t = rfOffset.top + (rfh - h) / 2;
                        l = rfOffset.left - w;
                        break;
                    case "tc":
                        t = rfOffset.top - h;
                        l = rfOffset.left + (rfw - w) / 2;
                        break;
                }
            }
            node.css({
                top: t,
                left: l
            });
        },
        atBody: function(node){
            var node = $(node), pos = node.css("position"), doc = Simple.getSize(document.body);
            if (pos == "fixed") {
                node.css({
                    top: (doc.h - node.height()) / 2,
                    left: (doc.w - node.width()) / 2
                });
            }
            else 
                if (pos == "absolute") {
                    node.css({
                        top: (doc.h - node.height()) / 2 + Math.max(document.documentElement.scrollTop, document.body.scrollTop),
                        left: (doc.w - node.width()) / 2
                    });
                }
        }
    }
    
    Simple.declare("dialog.Base", null, {
        node: null,
        title: "SimpleDialog",
        modal: true,
        position: "",
        ajax: "",
        loadingMessage: "加载中...",
        url: "",
        iframe: false,
        buttons: false,
        handleTool: ["close"],
        maxContainer: "body",
        width: "",
        height: "",
        data: "",
        color: "#000",
        opacity: 0.5,
        selectFix: true,
        onmin: $.noop,
        onmax: $.noop,
        onload: $.noop,
        onclose: $.noop,
        draggable: true,
        dialogTemplate: '<div class="simple-dialog"><table class="simple-dialog-table">' +
        '<tr class="handle"><td class="simple-dialog-tl"></td><td class="simple-dialog-tc" rel="dialogHead"><h2 class="simple-dialog-title" rel="dialogTitle"></h2></td><td class="simple-dialog-tr"></td></tr>' +
        '<tr><td class="simple-dialog-cl"></td><td class="simple-dialog-cc" ><div class="simple-dialog-content" rel="dialogBody"></div><div rel="dialogFoot"></div></td><td class="simple-dialog-cr"></td></tr>' +
        '<tr><td class="simple-dialog-bl"></td><td class="simple-dialog-bc"></td><td class="simple-dialog-br"></td></tr></table></div>',
        init: function(){
            this.dialog = $(this.dialogTemplate);
            this.head = this.dialog.find("[rel='dialogHead']");
            this.titleContainer = this.dialog.find("[rel='dialogTitle']");
            this.body = this.dialog.find("[rel='dialogBody']");
            this.foot = this.dialog.find("[rel='dialogFoot']");
            this._render();
        },
        destroy: function(){
            this.dialog.remove();
            this.modal.data("widget_modal").destroy();
			this.modal.data("widget_modal",false);
        },
        hide: function(){
            this.dialog.hide();
        },
        _render: function(){
            var s = this, bodyContent;
            if (this.modal) {
                this.modal = $(document.body).modal({
                    color: this.color,
                    opacity: this.opacity,
                    selectFix: this.selectFix
                });
            }
            if (this.node) {
                bodyContent = $(this.node).clone(true);
            }
            else 
                if (this.ajax) {
                    this.dialog.addClass("simple-dialog-ajax");
                    bodyContent = "<div class='simple-dialog-load'>" + this.loadingMessage + "</div>";
                    $.ajax({
                        url: this.url,
                        dataType: "html",
                        data: this.data,
                        success: function(r){
                            s.body.html(r);
                            s.setPosition();
                            s.onload.call(s.dialog);
                        },
                        error: function(){
                        
                        }
                    });
                }
                else 
                    if (this.iframe) {
                        this.dialog.addClass("simple-dialog-iframe");
                        bodyContent = '<div class="simple-dialog-load">' + this.loadingMessage + '</div><iframe class="simple-content-iframe" src="' + this.url + '" frameBorder="0" name="SimpleDialogFrame" style="display:none"></iframe>';
                    }
            this.body.html(bodyContent);
            this.titleContainer.html(this.title);
            this.setHandleTool();
            this.drawBtns();
            this.node = this.dialog;
            this.dialog.appendTo(document.body);
            if (this.iframe) {
                window["SimpleDialogFrame"].onload = function(){
                    s.body.find(".simple-dialog-load").remove();
                    s.body.find("iframe").fadeIn();
                    s.setPosition();
                }
            }
            this.dialog.width(this.width).height(this.height);
            this.setPosition();
            if (this.draggable) {
                this.dialog.drag({
                    handle: "[rel='dialogHead']"
                });
            }
        },
        setHandleTool: function(){
            var s = this;
            $.each(this.handleTool, function(i, n){
                var tool = $("<a/>").addClass("simple-dialog-" + n).attr("rel", "dialog" + n).html(n);
                tool.click(s["on" + n]);
                s.head.append(tool);
            });
            //设定关闭事件
            this.head.find("[rel='dialogclose']").click(function(){
                s.onclose.call(s.dialog);
                s.destroy();
            });
            //设定最大化事件
            this.head.find("[rel='dialogmax']").click(function(){
                if (s.dialog.data("max")) {
                    s.dialog.data("max", false);
                    s.dialog.css({
                        top: s.lastTop,
                        left: s.lastLeft,
                        width: s.lastWidth,
                        height: s.lastHeight
                    });
                }
                else {
                    s.lastTop = s.dialog.css("top");
                    s.lastLeft = s.dialog.css("left");
                    s.lastWidth = s.dialog.width();
                    s.lastHeight = s.dialog.height();
                    s.setSize();
                    s.dialog.data("max", true);
                }
            });
            //设定最小化事件
            this.head.find("[rel='dialogmin']").click(function(){
                s.onmin.call(s.dialog);
            });
        },
        setPosition: function(){
            if (this.position) {
                if (typeof this.position == "string") {
                    Simple.position.at(this.dialog, this.position, "cc");
                }
                else {
                    this.dialog.css({
                        top: this.position[1],
                        left: this.position[0]
                    });
                }
            }
            else {
                Simple.position.atBody(this.dialog);
            }
        },
        setHead: function(html){
            this.head.html(html);
        },
        setBody: function(html){
            this.body.html(html);
        },
        setFoot: function(html){
            this.foot.html(html);
        },
        setSize: function(){
            var maxCon = $(this.maxContainer), offset = maxCon.offset(), width = maxCon.width();
            height = maxCon.height();
            if (maxCon.is("body")) {
                height = $(window).height();
            }
            this.dialog.css(offset);
            this.dialog.width(width).height(height);
        },
        drawBtns: function(){
            var s = this,divWrap=$("<div>").addClass("simple-dialog-btn-wrap");
            if (this.buttons) {
                if (this.buttons instanceof Array) {
                    $.each(s.buttons, function(index, item){
                        var divBtn = $("<a/>").addClass("simple-btn").append("<span class='simple-btn-text'><i></i>" + item.text + "</span>");
                        if (item.cls) {
                            divBtn.addClass(item.cls);
                        }
                        if (item.ico) {
                            divBtn.find("i").addClass(item.ico);
                        }
                        if (item.event) {
                            item.click(item.event);
                        }
						divWrap.append(divBtn);
                    });
                }
                else {
                    $.each(s.buttons, function(key, value){
                        var divBtn = $("<a/>").addClass("simple-btn-blue simple-btn").append("<span class='simple-btn-text'>" + key + "</span>");
                        if (typeof value == "function") {
                            divBtn.unbind().bind("click", value);
                        }
                        if (key == "取消") {
                            divBtn.removeClass("simple-btn-blue").addClass("simple-btn-white");
                        }
                       divWrap.append(divBtn);
                    });
                }
				 s.foot.append(divWrap);
            }
        }
    });
    Simple.bridgeTojQuery("dialog,simpleDialog", Simple.dialog.Base);
    //便捷调用
    Simple.ajaxDialog=$.ajaxDialog=function(url,opts){
    	opts=$.extend({},opts,{
    		url:url,
    		ajax:true
    	})
    	return new Simple.dialog.Base(opts)
    }
    Simple.iframeDialog=$.iframeDialog=function(url,opts){
    	opts=$.extend({},opts,{
    		url:url,
    		iframe:true
    	})
    	return new Simple.dialog.Base(opts)
    }
    Simple.alert=$.alert=function(text,callback,opts){
    	opts=$.extend({},opts,{
    		buttons:{
    			"确定":function(){
    				if(typeof callback=="function"){
    					callback();
    				}
    				d.data("widget_dialog").destroy();
    			}
    		}
    	})
    	var d=$("<div class='simple-dialog-alert'>"+text+"</div>").dialog(opts);
    	return d.data("widget_dialog");
    }
    Simple.confirm=$.confirm=function(text,callback,opts){
    	opts=$.extend(opts,{
    		buttons:{
    			"确定":function(){
    				if(typeof callback=="function"){
    					callback();
    				}
    				d.data("widget_dialog").destroy();
    			},
    			"取消":function(){
    				if(typeof opts.oncancel=="function"){
    					opts.oncancel();
    				}
    				d.data("widget_dialog").destroy();
    			}
    		}
    	})
    	var d=$("<div class='simple-dialog-confirm'>"+text+"</div>").dialog(opts);
    	return d.data("widget_dialog");
    }
    //TODO:stack dialog 
    Simple.declare("dialog.Stack", Simple.dialog.Base, {
        init: function(){
        
        },
        destroy: function(){
            this.dialog.hide();
        }
    });
	
})();


